<template>
	<div class="addExpense">
		<el-button type="primary" plain @click="toBack">返回</el-button>
		<h3>报销详情</h3>
		<el-form label-position="top" :model="expense" :rules="rules" ref="ruleForm">
			<el-form-item label="申请人" style="width: 500px;"
				v-if="expense.id !== null">
				<el-input :value="expense.userName" readonly>
				</el-input>
			</el-form-item>
			<el-form-item label="报销金额" style="width: 500px;">
				<el-input v-model="expense.price" type="number" placeholder="报销金额" 	
					step="0.01" @input="checkPrice">
				</el-input>
			</el-form-item>
			<el-form-item label="报销说明" prop="info" style="width: 500px;">
				<el-input type="textarea" v-model="expense.info"
					:autosize="{ minRows: 4, maxRows: 6}" placeholder="报销说明">
				</el-input>
			</el-form-item>
			<el-form-item label="备注" style="width: 500px;">
				<el-input v-model="expense.remarks" type="textarea"
					:autosize="{ minRows: 4, maxRows: 6}" placeholder="备注">
				</el-input>
			</el-form-item>
			<el-form-item label="附加图">
				<div style="display: flex;">
					<div class="order-img-div" v-for="(item,index) in expense.imageUrl"
						:key="index" style="position: relative;margin-right: 10px;"
						v-if="expense.imageUrl.length > 0">
						<el-image :src="READ_IMG_URL+item" class="htimg"
							:preview-src-list="addUrl(expense.imageUrl)">
						</el-image>
						<i class="el-icon-close hover-icon" @click="deleteImg(index)"></i>
					</div>
					<img v-if="expense.imageUrl.length < 3" :src="image" class="htimg" 
						@click="selectFile" />
				</div>
			</el-form-item>
			<el-form-item v-if="!readonly" style="width: 100%;">
				<el-button @click="reset">重置</el-button>
				<el-button type="primary" @click="onSubmit">申请</el-button>
			</el-form-item>
		</el-form>
		<input type="file" id="fileInput" ref="fileInput" style="display: none" @change="handleFileChange" />
	</div>
</template>

<script>
	// import {
	// 	UploadFile
	// } from "../../api/all.js";
	import warehouseApi from "../../api/warehouse.js";
	import uploadFile from "../../api/uploadFile.js";
	import config from '../../api/apiURL.js';
	export default {
		data() {
			return {
				READ_IMG_URL: config.READ_IMG_URL,
				userInfo: {},
				image: "",
				selectedFile: null,
				readonly: false,
				expense: {
					id: null,
					price: 0.00,
					info: null,
					remarks: null,
					image: null,
					imageUrl: [],
				},
				rules: {
					info: [{
						required: true, message: '请输入报销说明', trigger: 'blur'
					}]
				}
			}
		},
		created() {
			this.userInfo = JSON.parse(localStorage.getItem("userInfo"))
			const id = localStorage.getItem("expenseId");
			if (id) {
				this.expense.id = id
				this.getExpense();
			}
			this.image = "https://kris-k.oss-cn-hangzhou.aliyuncs.com/kris/c179093a-41b0-4c70-bc1f-6e5973f35c98-jia.png";
		},
		destroyed() {
			localStorage.removeItem("expenseId")
		},
		methods: {
			// 返回上个页面
			toBack() {
				this.$router.push({
					path: "/expense/Expense"
				})
			},
			// 获取报销单
			getExpense(){
				const loading = this.$loading({
				    lock: true,
				    text: 'Loading',
				    spinner: 'el-icon-loading',
				    background: 'rgba(0, 0, 0, 0.7)'
				});
				const data ={
					id: this.expense.id
				}
				warehouseApi.getExpense(data).then(res =>{
					if (res.code === 200){
						this.expense = res.data;
					}
				}).finally(() =>{
					loading.close();
				})
			},
			// 检查数字，小于0.00，或者超过小数点后两位返回0
			checkNumber(value) {
				if (value < 0.00) {
					value = 0;
				}
				// 使用正则表达式匹配小数点后两位以内的数字或整数
				let regex = /^\d+(\.\d{1,2})?$/;
				if (!regex.test(value)) {
					value = 0
				}
				return value;
			},
			// 检查输入的金额
			checkPrice(e){
				let inputNumber = parseFloat(this.expense.price);
				inputNumber = this.checkNumber(inputNumber);
				this.expense.price = inputNumber
			},
			// 点击上传图片
			selectFile() {
				this.$refs.fileInput.click();
			},
			// 上传oos
			handleFileChange(event) {
				this.selectedFile = event.target.files[0];
				// 上传前验证
				const fileSuffix = this.selectedFile.name.substring(this.selectedFile.name.lastIndexOf(".") + 1);
				const whiteList = ["jpg", "jpeg", "png", "JPG", "JPEG", "PNG"];
				if (whiteList.indexOf(fileSuffix) === -1) {
					this.$message.error("上传文件只能是 jpg、png格式！");
					return;
				}
				const isLt5M = this.selectedFile.size / 1024 / 1024 < 5;
				if (!isLt5M) {
					this.$message.error('上传的图片大小不能超过5MB!');
					return;
				}
				// this.image = URL.createObjectURL(this.selectedFile);
				this.uploadImage();
			},
			//发送上传文件api
			uploadImage() {
				const loading = this.$loading({
					lock: true,
					text: '上传中...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				let formData = new FormData();
				formData.append("file", this.selectedFile);
				uploadFile.uploadImage(formData).then(res =>{
					if (res.code === 200){
						const url = res.data
						this.expense.imageUrl.push(url);
						this.$message.success("上传成功")
					}
				}).finally(() =>{
					this.selectedFile = '';
					loading.close();
				})
				// UploadFile(formData).then((data) => {
				// 	let url = data.data;
				// 	this.expense.imageUrl.push(url);
				// 	this.$message.success("上传成功");
				// 	this.image = "https://kris-k.oss-cn-hangzhou.aliyuncs.com/kris/c179093a-41b0-4c70-bc1f-6e5973f35c98-jia.png"
				// });
			},
			// 删除图片
			deleteImg(index){
				this.expense.imageUrl.splice(index,1);
			},
			// 重置
			reset(){
				this.expense.price= 0.00;
				this.expense.info = null;
				this.expense.remarks = null;
				this.expense.image= null;
				this.expense.imageUrl= [];
				this.$refs.ruleForm.resetFields();
			},
			// 提交
			onSubmit() {
				let _this = this;
				this.$refs.ruleForm.validate((valid) => {
					if (!valid){
						_this.$message.error("请将表单填写完整！")
						return false;
					}
					
					if (_this.expense.imageUrl !== null && _this.expense.imageUrl.length > 0){
						_this.expense.image = "";
						for (var i = 0; i < _this.expense.imageUrl.length; i++) {
							if (i === _this.expense.imageUrl.length-1){
								_this.expense.image=_this.expense.image+_this.expense.imageUrl[i]
							}else {
								_this.expense.image=_this.expense.image+_this.expense.imageUrl[i]+";"
							}
						}
					}
					if (_this.expense.id == null){
						// 新增
						warehouseApi.addExpense(this.expense).then(res =>{
							this.$message.success("添加成功")
							this.reset();
						})
					}else {
						// 修改
						warehouseApi.updateExpense(this.expense).then(res =>{
							this.$message.success("修改成功");
							this.getExpense();
						})
					}
				});
			},
			addUrl(list){
				let newList = []
				list.forEach(item =>{
					newList.push(this.READ_IMG_URL+item)
				})
				return newList;
			}
		}
	}
</script>

<style>
	
	.expenseImg{
		width: 150px;
		height: 150px;
		margin-right: 10px;
	}
	
	.htimg {
		width: 150px;
		height: 150px;
		object-fit: cover;
		/* 保持原始宽高比，填充容器 */
	}
	
	.order-img-div{
		width: 150px;
		height: 150px;
	}
	
	.order-img-div:hover .hover-icon{
		display: block;
	}
	
	.hover-icon{
		display: none;
		font-size: 24px;
		position: absolute;
		top: 0; 
		right: 0;
		color: #ffffff;
		background-color: black;
		opacity: 0.9
	}
	
	.hover-icon:hover{
		cursor: pointer;
	}
</style>